<template>
  <div class="team-add-wrap">
    <div class="team-add-ico">
      <img src="@/common/image/create-team-left.png" alt="">
    </div>
    <div class="team-add-con">
      <h2>创建团队</h2>
      <div class="team-add-information">
        <el-form
          :model="teamInformationForm"
          label-position="top"
          :hide-required-asterisk="hideRequiredAsteriskBtn"
          ref="teamInformationForm"
          :rules="rulesteamInformationForm">
          <el-form-item label="团队名称" class="information-item" prop="teamName">
            <el-input
              placeholder="有字母、数字或下划线组成，名称不能重复"
              v-model="teamInformationForm.teamName"
              autocomplete="off"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="团队简介" class="information-item" prop="teamText">
            <el-input
              placeholder="对团队做简单的描述"
              v-model="teamInformationForm.teamText"
              autocomplete="off"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="添加成员" class="information-item item-information-email" prop="teamAddEmail">
            <div class="information-email">
              <div class="information-email-msg" :class="{'information-email-msg-btn': isEmailBorderBtn}">
                <el-input
                  placeholder="输入邮箱号进行邀请"
                  v-model="teamInformationForm.teamAddEmail"
                  autocomplete="off"
                  clearable>
                </el-input>
              </div>
              <div class="information-email-btn" @click="addPersonnelFun">搜索</div>
            </div>
            <ul class="information-email-back" v-if="accordingEnd">
              <li class="back-item">
                <div class="back-item-portrait">
                  <img :src="memberIcoSeparate ? memberIcoSeparate : dattSetImgUrl" alt="">
                </div>
                <p class="back-item-con">
                  <span>{{memberNameSeparate}}</span>{{memberEmailSeparate}}
                </p>
                <div class="back-item-add" @click="addMembersIDfun" @mouseover="addmebershow=true" @mouseleave="addmebershow=false">
                  <img v-if="addmebershow" src="@/common/image/team-add-people-active.png" alt="">
                  <img v-else src="@/common/image/team-add-people.png" alt="">
                </div>
              </li>
            </ul>
          </el-form-item>
          <div class="team-personnel-list" v-if="teamPersonnelList.length>0">
            <ul class="personnel-list-wrap">
              <li
                class="personnel-item"
                v-for="(item, index) in teamPersonnelList"
                :key="index">
                <div class="personnel-item-ico">
                  <img :src="item.teamIco ? item.teamIco : dattSetImgUrl" alt="">
                </div>
                <div class="personnel-item-text">
                  <p class="item-text-name">{{item.teamName}}</p>
                  <p class="item-text-email">{{item.teamEmail}}</p>
                </div>
                <div class="personnel-item-dele" @click="delePersonnelFun(index)">
                  <img src="@/common/image/delete-members.png" alt="">
                </div>
              </li>
            </ul>
          </div>
          <el-form-item class="submitbtn">
            <el-button type="primary" @click="submitTeamItemForm('teamInformationForm')">创建</el-button>
          </el-form-item>
        </el-form>
        <p class="team-add-instructions">说明：成员将可以使用您账户的算力。您也可以在数据统计中选择禁止成员使用您的算力</p>
      </div>
    </div>
  </div>
</template>

<script>
import { creatPaiTeam, getUserInfoByEmail } from '@/api/team_list'
import dataSetImg from '@/common/image/dataset.jpg'
import { mapGetters } from 'vuex'
import qs from 'qs'

export default {
  inject: ['reload'],
  data () {
    // 团队名称验证
    var validateName = (rule, value, callback) => {
      var reg1 = /^[a-zA-Z0-9_]*$/
      var reg2 = /^[a-zA-Z0-9]{1}[a-zA-Z0-9_]*$/
      if (!reg1.test(value)) {
        callback(new Error('团队名称仅支持字母、数字和下划线'))
      } else if (!reg2.test(value)) {
        callback(new Error('团队名称不能以下划线开头'))
      } else {
        callback()
      }
    }
    // 邮箱验证
    var checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      this.isEmailBorderBtn = false
      setTimeout(() => {
        if (mailReg.test(value)) {
          this.inputTeamAddEmail = true
          callback()
        } else if (value === '') {
          this.isEmailBorderBtn = true
          this.inputTeamAddEmail = false
          callback()
        } else {
          this.inputTeamAddEmail = false
          callback(new Error('邮箱格式不正确'))
        }
      }, 100)
    }
    return {
      inputTeamAddEmail: false,
      isEmailBorderBtn: false,
      memberIcoSeparate: '',
      memberNameSeparate: '',
      memberEmailSeparate: '',
      memberIdSeparate: '',
      memberEmailAll: [],
      teamPersonnelList: [],
      accordingEnd: false,
      addmebershow: false,
      // 默认图片
      dattSetImgUrl: dataSetImg,
      // 搜索避免重复点击
      addRepeatBtn: true,
      teamInformationForm: {
        teamName: '',
        teamText: '',
        teamAddEmail: ''
      },
      rulesteamInformationForm: {
        teamName: [
          { required: true, message: '请输入团队名称', trigger: 'blur' },
          { validator: validateName },
          { max: 50, message: '名称长度须在1到50个字符之间' }
        ],
        teamText: [
          { required: true, message: '请输入团队简介', trigger: 'blur' },
          { max: 100, message: '简介内容不能超过100个字符' }
        ],
        teamAddEmail: [
          { validator: checkEmail, trigger: 'blur' }
        ]
      },
      hideRequiredAsteriskBtn: true
    }
  },

  components: {},

  computed: {
    ...mapGetters([
      'userInfo'
    ])
  },

  mounted () {},

  destroyed () {
  },

  methods: {
    // 搜索邮箱对应账户
    addPersonnelFun () {
      if (this.inputTeamAddEmail) {
        for (var i = 0; i < this.memberEmailAll.length; i++) {
          if (this.memberEmailAll[i] === this.teamInformationForm.teamAddEmail) {
            this.$message({ message: '您已添加邀请该成员', showClose: true, type: 'error' })
            return false
          }
        }
        if (this.addRepeatBtn) {
          if (this.userInfo.email === this.teamInformationForm.teamAddEmail) {
            this.$message({ message: '您不能添加自己为成员', showClose: true, type: 'error' })
            return false
          } else {
            this.addRepeatBtn = false
            this._getUserInfoByEmail()
          }
        }
      }
    },
    // 点击发送邀请码
    addMembersIDfun () {
      if (this.memberIdSeparate) {
        this.memberEmailAll.push(this.memberEmailSeparate)
        let personnelObj = {}
        personnelObj.teamName = this.memberNameSeparate
        personnelObj.teamEmail = this.memberEmailSeparate
        personnelObj.teamIco = this.memberIcoSeparate
        this.teamPersonnelList.push(personnelObj)
        this.accordingEnd = false
      }
    },
    // 删除邀请团队成员
    delePersonnelFun (agm) {
      this.teamPersonnelList.splice(agm, 1)
      this.memberEmailAll.splice(agm, 1)
    },
    submitTeamItemForm (agm) {
      this.$refs[agm].validate((valid) => {
        if (valid) {
          this.isEmailBorderBtn = true
          this._creatPaiTeam()
        } else {
          this.isEmailBorderBtn = true
          return false
        }
      })
    },
    // 创建团队
    _creatPaiTeam () {
      const memberEmailAllStr = this.memberEmailAll.join(',')
      let data = qs.stringify({
        name: this.teamInformationForm.teamName,
        introduction: this.teamInformationForm.teamText,
        emails: memberEmailAllStr
      })
      creatPaiTeam(data).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: '创建团队成功！', showClose: true, type: 'success' })
          this.reload()
          this.$router.push({ path: '/team/detail/member', query: { id: res.data.id, role: 1 } })
        } else if (res.message.code === 20002) {
          this.$message({ message: '您已创建过团队', showClose: true, type: 'error' })
        } else if (res.message.code === 20001) {
          this.$message({ message: '团队名称已存在', showClose: true, type: 'error' })
        }
      })
    },
    // 邮箱搜索
    _getUserInfoByEmail () {
      let data = qs.stringify({
        email: this.teamInformationForm.teamAddEmail,
        teamId: '-1'
      })
      getUserInfoByEmail(data).then(res => {
        if (res.message.code === 0) {
          this.memberNameSeparate = res.data.username
          this.memberEmailSeparate = res.data.email
          this.memberIdSeparate = res.data.id
          this.memberIcoSeparate = res.data.headImage
          this.accordingEnd = true
          this.addRepeatBtn = true
        } else if (res.message.code === 5) {
          this.addRepeatBtn = true
          this.$message({ message: '该用户不存在', showClose: true, type: 'error' })
          this.addRepeatBtn = true
        } else if (res.message.code === 20004) {
          this.addRepeatBtn = true
          this.$message({ message: '用户已加入团队', showClose: true, type: 'error' })
        } else {
          this.addRepeatBtn = true
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
    }
  }
}

</script>
<style lang="stylus">
team-item-style(numl)
  word-break break-all
  word-wrap break-word
  overflow hidden
  text-overflow ellipsis
  display -webkit-box
  /*! autoprefixer: off */
  -webkit-box-orient vertical
  /* autoprefixer: on */
  -webkit-line-clamp numl
$fontcolor = #2D323B
.team-add-wrap
  width 100%
  margin 0 auto
  max-width 1162px
  display flex
  padding-top 64px
  .team-add-ico
    width 124px
    height 69px
    margin-right 47px
    img
      width 100%
      height 100%
  .team-add-con
    flex 1
    h2
      font-size 28px
      line-height 40px
      color $fontcolor
      font-weight bold
      padding 36px 0 42px
    .team-add-information
      .team-add-instructions
        font-size 14px
        line-height 22px
        color #8D9091
        width 433px
      .submitbtn
        margin-top 75px
        .el-button
          width 200px
          padding 10px
          font-size 16px
          line-height 22px
          background #2E94F9
          border-radius 3px
      .information-item
        width 433px
        .el-form-item__label
          font-size 14px
          line-height 20px
          color #2D323B
          padding 11px 0
          font-weight bold
      .item-information-email
        position relative
      .el-form-item
        margin-bottom 13px
        .information-email-back
          position absolute
          bottom -62px
          left 0
          .back-item
            display flex
            align-items center
            width 337px
            background #ffffff
            border 1px solid #cccccc
            border-radius 4px
            padding 25px 21px 13px 14px
            .back-item-portrait
              width 20px
              height 20px
              font-size 0
              margin-right 7px
              border-radius 50% 50%
              overflow hidden
              img
                width 100%
                height 100%
            .back-item-con
              width 250px
              font-size 12px
              color #666666
              line-height 17px
              word-break break-all
              word-wrap break-word
              overflow hidden
              text-overflow ellipsis
              display -webkit-box
              /*! autoprefixer: off */
              -webkit-box-orient vertical
              /* autoprefixer: on */
              -webkit-line-clamp 1
              span
                font-size 14px
                line-height 20px
                color $fontcolor
                margin-right 9px
            .back-item-add
              float right
              width 14px
              height 14px
              margin-top 2px
              font-size 0
              cursor pointer
              img
                display block
                width 100%
                height 100%
        .information-email
          display flex
          justify-content space-between
          .information-email-msg
            width 337px
          .information-email-msg-btn
            .el-input__inner
              border-color #c0c4cc
          .information-email-btn
            width 88px
            height 40px
            line-height 40px
            text-align center
            font-size 14px
            color $fontcolor
            background #F4F7F8
            border-radius 4px
            cursor pointer
      .team-personnel-list
        width 433px
        max-height 250px
        overflow-x hidden
        overflow-y auto
        margin-top 24px
        .personnel-list-wrap
          height auto
          .personnel-item
            height 42px
            margin-bottom 24px
            overflow hidden
            display flex
            align-items center
            .personnel-item-ico
              width 40px
              height 32px
              border-radius 50% 50%
              overflow hidden
              margin-right 12px
              img
                width 32px
                height 32px
            .personnel-item-text
              width 445px
              .item-text-name
                team-item-style(1)
                font-size 14px
                line-height 20px
                color #2E94F9
              .item-text-email
                team-item-style(1)
                font-size 14px
                line-height 20px
                color #666666
                margin-top 2px
            .personnel-item-dele
              width 20px
              height 20px
              display flex
              cursor pointer
              justify-content center
              align-items center
              img
                width 11px
                height 11px
          .personnel-item:nth-last-of-type(1)
            margin-bottom 0
</style>
